﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using Agr.CQRS.Domain.Events;
using System.IO;

namespace Agr.CQRS.Infrastructure.Events
{
    class StoredDomainEvent
    {
        private static BinaryFormatter bf = new BinaryFormatter();

        public virtual int Id { get; set; }
        public virtual Guid AggregateRootId { get; set; }
        public virtual int Version { get; set; }
        public virtual int EntityNumber { get; set; }
        public virtual Byte[] SerializedEvent { get; set; }

        public virtual DomainEvent GetEvent()
        {
            DomainEvent ev;
            using (var ms = new MemoryStream(SerializedEvent))
                ev = bf.Deserialize(ms) as DomainEvent;

            ev.Version = Version;
            ev.AggregateRootId = AggregateRootId;
            ev.Entitynumber = EntityNumber;

            return ev;
        }

        public virtual void WrapEvent(DomainEvent ev)
        {
            using (var ms = new MemoryStream())
            {
                bf.Serialize(ms, ev);
                ms.Position = 0;

                using (var r = new BinaryReader(ms))
                    SerializedEvent = r.ReadBytes((int)ms.Length);
            }

            AggregateRootId = ev.AggregateRootId;
            Version = ev.Version;
            EntityNumber = ev.Entitynumber;
        }

    }
}
